package com.caipos.actor.common.msg;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public final class KbMsgProcessingCtx implements Serializable {

    private final AtomicInteger ruleNodeExecCounter;
    private volatile LinkedList<KbMsgProcessingStackItem> stack;

    public KbMsgProcessingCtx() {
        this(0);
    }

    public KbMsgProcessingCtx(int ruleNodeExecCounter) {
        this(ruleNodeExecCounter, null);
    }

    protected KbMsgProcessingCtx(int ruleNodeExecCounter, LinkedList<KbMsgProcessingStackItem> stack) {
        this.ruleNodeExecCounter = new AtomicInteger(ruleNodeExecCounter);
        this.stack = stack;
    }

    public int getAndIncrementRuleNodeCounter() {
        return ruleNodeExecCounter.getAndIncrement();
    }

    public KbMsgProcessingCtx copy() {
        if (stack == null || stack.isEmpty()) {
            return new KbMsgProcessingCtx(ruleNodeExecCounter.get());
        } else {
            return new KbMsgProcessingCtx(ruleNodeExecCounter.get(), new LinkedList<>(stack));
        }
    }
}
